package rsj.proxy.bind;

import com.rlyy.aibase.utils.base.ThinkException;
import org.springframework.stereotype.Component;
import rsj.proxy.parse.ParameterMapping;
import rsj.proxy.parse.SqlSource;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 默认sql参数绑定
 *
 * @author yuanqinglong
 * @date 2021/05/24
 * @since 2021/5/24 11:03
 */
@Component
public class DefaultParamResolve extends AbstractParamResolveFactory{


    /**
     * 参数解析器工厂
     *
     * @param paramResolveProcessors 参数解决处理器
     */
    public DefaultParamResolve(List<ParamResolveProcessor> paramResolveProcessors) {
        super(paramResolveProcessors);
    }

    /**
     * 解析绑定参数
     *
     * @param method    方法
     * @param args      arg游戏
     * @param sqlSource sql源
     * @return {@link Object[]}
     * @throws Exception 异常
     */
    @Override
    public Object[] doParameterAnalysis(SqlSource sqlSource, Method method, Object[] args) throws Exception {
        // 解析后的参数值集合
        List<Object> paramValueList = new ArrayList<>();
        List<ParameterMapping> parameterMappings = sqlSource.getParameterMappings();
        // 按照原始sql中占位符名字顺序绑定参数
        for (ParameterMapping parameterMapping : parameterMappings) {
            ParamResolveProcessor paramResolveProcessor = paramResolveProcessorMap.get(parameterMapping.getMethodParamTypeEnum());
            if (Objects.isNull(paramResolveProcessor)) {
                throw new ThinkException("无法解析(" + parameterMapping.getMethodParamTypeEnum() + ") 类型参数");
            }
            paramResolveProcessor.doParamResolve(sqlSource, parameterMapping, method, args, paramValueList);
        }
        return paramValueList.toArray();
    }


}
